package com.lenovo.leos.filebrowser.engine.util;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.ArrayList;



public class HistoryManager extends Object {
	private static final String TAG = "HistoryManager";

	public interface OnHistoryUpdatedListener {
		void onHistoryUpdated(HistoryManager lh);
	}
		
	private LinkedList<HistoryItem> mHIQueue = null;
	private OnHistoryUpdatedListener mListener = null;
	private boolean isUpdateAtOnce = true;
		
	private static HistoryManager sInstance = new HistoryManager();
	
	public synchronized static HistoryManager getInstance(){
		return sInstance;
	}
	
	private final void notifyObserver() {
		Log.i(TAG, "==> notifyObserver");		
		if (null != mListener){
			Log.i(TAG, "==> notifyObserver");
			mListener.onHistoryUpdated(this);
		}
	}
	
	private HistoryManager(){
		if (null == mHIQueue)
			mHIQueue = new LinkedList<HistoryItem>();
	}
	
	public void setisUpdateAtOnce(boolean needOrNot) {
		isUpdateAtOnce = needOrNot;
	}
	
	public void pushHI(HistoryItem hi) {
		if (null != hi) {
			mHIQueue.addFirst(hi);
			updateInternal();
		}
	}
	
	public HistoryItem popHI() {
		if (mHIQueue.size() != 0) {
			HistoryItem hi = mHIQueue.poll();
			updateInternal();
			return hi;
		}else 
			return null;
	}
	
	public HistoryItem getCurHI() {
		if(mHIQueue.isEmpty())
			return null;
		else
			return mHIQueue.getFirst();
	}
	
	public HistoryItem getPrevHI() {
		return mHIQueue.get(1);
	}
		
	public void rollBack() {
		mHIQueue.poll();
		updateInternal();		
	}
	
	public void clearAll() {
		mHIQueue.clear();
		updateInternal();
	}
	
	public void replaceLast(HistoryItem hi) {
		if (0 != mHIQueue.size())
			mHIQueue.poll();
		mHIQueue.addFirst(hi);
		updateInternal();
	}
	
	public ListIterator<HistoryItem> getIterator() {
		return mHIQueue.listIterator();
	}
	
	public int getSize() {
		return mHIQueue.size();
	}
	
	public void setOnHistoryUpdatedListener(OnHistoryUpdatedListener mHistoryListener) {
		mListener = mHistoryListener;
	}
	
	public void update() {
		notifyObserver();
	}
	
	private void updateInternal() {
		if (isUpdateAtOnce)
			notifyObserver();
	}
	
	public void getHistoryFromSerializable(Serializable serial) {
		if (!mHIQueue.isEmpty())
			mHIQueue.clear();
		ArrayList<HistoryItem> temp = (ArrayList<HistoryItem>)serial;
		
		for (HistoryItem loc : temp) {
			if(null!= loc)
				mHIQueue.add(loc.clone());
		}
	}
	
	public Serializable putHistoryToSerializable() {
		if(null == mHIQueue || mHIQueue.isEmpty())
			return null;
		else {
			ArrayList<HistoryItem> temp = new ArrayList<HistoryItem>();
			for (HistoryItem hi : mHIQueue){
				if (null != hi)
					temp.add(hi.clone());
			}
			return temp;
		}
	}
	
	
	
	// for test
	public void dump() {
		ListIterator<HistoryItem> iterator = mHIQueue.listIterator();
		while(iterator.hasNext()){
			HistoryItem loc = iterator.next();
			loc.dump();
		}
	}
			
}
